//
//  CoreDataManager.m
//  UseData
//
//  Created by Lenny on 16/5/16.
//  Copyright © 2016年 Lenny. All rights reserved.
//

#import "CoreDataManager.h"
#import <CoreData/CoreData.h>
#import <objc/runtime.h>

@implementation CoreDataManager

//单列
+ (instancetype)share {
    
    static CoreDataManager *intance = nil;
    static dispatch_once_t once;
    dispatch_once(&once, ^{
       
        intance = [[CoreDataManager alloc] init];
        intance.myAppDelegate = [UIApplication sharedApplication].delegate;
    });
    return intance;
}

//根据enityName设置模型
- (id)setEnityWithString:(NSString *)enityName {
    
    id model = [NSEntityDescription insertNewObjectForEntityForName:enityName inManagedObjectContext:self.myAppDelegate.managedObjectContext];
    return model;
}

//根据sql条件查看数据
- (id)checkWithEnity:(NSString *)enityName withSql:(NSString *)sqlStr {
    
    NSFetchRequest *request = [[NSFetchRequest alloc] init];
    id model = [NSEntityDescription entityForName:enityName inManagedObjectContext:self.myAppDelegate.managedObjectContext];
    [request setEntity:model];
    //查询条件
    if (![sqlStr isEqual:@""]) {
        NSPredicate *predicate = [NSPredicate predicateWithFormat:sqlStr];
        [request setPredicate:predicate];
    }
    NSError *error = nil;
    NSMutableArray *arr =[[self.myAppDelegate.managedObjectContext executeFetchRequest:request error:&error] mutableCopy];
    if (arr == nil) {
        NSLog(@"Error:%@",error);
    }
    return arr;
}

//根据条件查找要删除数据，返回为nil sqlStr:为sql语句
- (void)deleteWithEnity:(NSString *)enityName withSql:(NSString *)sqlStr {
    
    NSMutableArray *arr = [self checkWithEnity:enityName withSql:sqlStr];
    for (id model in arr) {
        [self.myAppDelegate.managedObjectContext deleteObject:model];
    }
}

//存储数据
- (void)saveData {

    NSError *error;
    BOOL isSaveS = [_myAppDelegate.managedObjectContext save:&error];
    if (!isSaveS) {
        NSLog(@"Error:%@",error);
    }else {
        NSLog(@"Save successfull!");
    }
}

@end
